﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace VSA.Applications
{
    public class ThreadExceptionHandler
    {
        /// 
        /// Handles the thread exception.
        /// 
        public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            try
            {
                // Exit the program if the user clicks Abort.

                DialogResult result = ShowThreadExceptionDialog(e.Exception, "Thread");

                if (result == DialogResult.Abort)
                {
                    Application.Exit();
                }
            }
            catch
            {
                // Fatal error, terminate program
                try
                {
                    MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }

                finally
                {
                    Application.Exit();
                }
            }
        }

        /// 
        /// Creates and displays the error message.
        /// 
        private DialogResult ShowThreadExceptionDialog(Exception ex, string type)
        {
            string errorMessage =
            type + " Exception:\n\n" +
            ex.GetType() +
            "\n\nError Message:\n" +
            ex.ToString();

            //maybe errorMessage is too long,which make users can't close MessageBox
            if (errorMessage.Length > 600)
                errorMessage = errorMessage.Substring(0, 600) + "......";
            return MessageBox.Show(errorMessage,"Error");
        }

        public void AppDomain_UnHandledException(object sender, System.UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is System.Exception)
            {
                DialogResult result = ShowThreadExceptionDialog((System.Exception)e.ExceptionObject, "Unhandled");

                if (result == DialogResult.Abort)
                {
                    Application.Exit();
                }
            }
        }

    } // End ThreadExceptionHandler
}
